/**
 * Bestpay.com.cn Inc.
 * Copyright (c) 2011-2020 All Rights Reserved.
 */
package com.suxiaoxiao.springbootlearn.designpattern.statepattern.badcode;

import lombok.ToString;

/**
 * 不好的代码
 *
 * @author zhaorongzhang
 * @version BadCode.java, v 0.1 2020/1/9 8:33 下午 zhaorongzhang Exp $$
 */
@ToString
public class BadGumballMachine {

    /**
     * 售尽
     */
    final static int SOLD_OUT = 0;
    /**
     * 没投币
     */
    final static int NO_QUARTER = 1;
    /**
     * 已投币
     */
    final static int HAS_QUARTER = 2;
    /**
     * 出售中
     */
    final static int SOLD = 3;

    /**
     * 当前状态
     */
    int state = SOLD_OUT;

    /**
     * 机器中糖果的数量
     */
    int count = 0;

    public BadGumballMachine(int count) {
        this.count = count;
        if (count > 0) {
            state = NO_QUARTER;
        }
    }

    /**
     * 投币
     */
    public void insertQuarter() {
        if (state == HAS_QUARTER) {
            System.out.println("已经投币了，不用再投一次。");
        } else if (state == SOLD_OUT) {
            System.out.println("卖完了");
        } else if (state == SOLD) {
            System.out.println("请等待，正在准备糖果。");
        } else if (state == NO_QUARTER) {
            state = HAS_QUARTER;
            System.out.println("已投币");
        }
    }

    /**
     * 退币
     */
    public void ejectQuarter() {
        if (state == HAS_QUARTER) {
            System.out.println("退币中");
            state = NO_QUARTER;
        } else if (state == NO_QUARTER) {
            System.out.println("您没有投币");
        } else if (state == SOLD) {
            System.out.println("您已经买了糖果，无法退款。");
        } else if (state == SOLD_OUT) {
            System.out.println("您无法退币，您从未投过币。");
        }
    }

    /**
     * 转动曲柄
     */
    public void turnCrank() {
        if (state == SOLD) {
            System.out.println("别想骗过机器拿两次糖果");
        } else if (state == NO_QUARTER) {
            System.out.println("请您投币");
        } else if (state == SOLD_OUT) {
            System.out.println("已售尽");
        } else if (state == HAS_QUARTER) {
            System.out.println("糖果生成中");
            state = SOLD;
            dispense();
        }
    }

    /**
     * 发放糖果
     */
    public void dispense() {
        if (state == SOLD) {
            System.out.println("请取走您的糖果");
            count = count - 1;
            if (count == 0) {
                System.out.println("糖果已售尽");
                state = SOLD_OUT;
            } else {
                state = NO_QUARTER;
            }
        } else if (state == NO_QUARTER) {
            System.out.println("请您先投币");
        } else if (state == SOLD_OUT) {
            System.out.println("已售尽");
        } else if (state == HAS_QUARTER) {
            System.out.println("已售尽");
        }
    }

}